<?php 

/**
 * Class MongoLAutoIncrease
 *
 * 继承MongoLModel 用于维护自增ID
 * @author hwz
 */
class MongoLAutoIncrement extends MongoLModel {

    /**
     * 集合名称
     *
     * @var string
     */
    protected $collectionName = 'auto_increment';

    /**
     * seq
     * @param string $collection_name MongoDB中的集合名称
     * @return void
     * @author hwz
     **/
    public static function seq($collection_name) {
        $self = new static();
        $one = self::where(array(
            'name'=>$collection_name
        ))->getOne();
        if ($one) {
            $ret = $self->collection->findAndModify(
                array(
                    'name'=>$collection_name,
                ), 
                array(
                    '$inc'=>array(
                        'seq'=>1,
                    ),
                ),
                null,
                array('new'=>true,'upsert'=>true)
            );
            $seq = $ret['seq'];
        }else{
            $cursor = $self->connection->database->$collection_name->find()->sort(array('_id'=>-1))->limit(1);
            $cursor->next();
            $max = $cursor->current();
            $seq = $max ? $max['_id'] : 0;
            $self->name = $collection_name;
            $self->seq = ++$seq;
            $self->save();
        }
        return $seq;
    }
}


//end of file
